package com;

import com.fz.entity.Book;
import com.fz.mapper.BookMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

;
;

/**
 * Created by ZCY on 2018-01-17.
 */
public class Demo {
    protected SqlSession session = null;

    @Before
    public void init() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
        this.session = sf.openSession();
    }

    @After
    public void close() {
        session.commit();
        session.close();
    }

    /*增加商品*/
    @Test
    public  void add(){
        BookMapper bm = this.session.getMapper(BookMapper.class);
        Book b = new Book();
        b.setName("《疯狂马克思》");
        b.setAuthor("小李飞刀");
        b.setPrice(877.9);
        b.setFlag('y');
        b.setIntro("哼哼！！");
        //  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        b.setCtime(new Date());
     //   bm.insert(b);
        /*指定的添加商品*/
        //bm.add("夏末一个美女","张明朗",120.9,new Date());
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("author","飞天");
        map.put("price",799.0);
        map.put("ctime",new Date());
        map.put("name","《mysql技术》");
        bm.save(map);

}
  /*查询数据库中的所有的表*/
  @Test
  public void queryTables(){
      BookMapper bm = this.session.getMapper(BookMapper.class);
      //使用for循环把所有的数据库中的表进行便利出来
      for(String str:bm.querytables()){
          System.out.println("mysql数据库中的所有的表="+str);
      }
  }

  /*删除数据库中的数据*/
  @Test
   public void delete(){
        BookMapper bm = this.session.getMapper(BookMapper.class);
        bm.deletaById(7);
   }




    /*查询*/
    @Test
    public  void query() {
        BookMapper bk =  session.getMapper(BookMapper.class);
        List<Book> list = bk.query();
        System.out.println(list.size());
        for(Book b:list){
            System.out.println(b.getId());
            System.out.println(b.getName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            System.out.println(sdf.format(b.getCtime()) );


        }
    }

    /*对数据库中的数据进行更新*/
    @Test
    public void updata(){
        BookMapper bm = this.session.getMapper(BookMapper.class);
      //  Book b = bm.queryId(1);
      //  b.setPrice(30);
    //    bm.update(b);
        /*根基id改价格*/
        bm.updatebid(1,9999);



    }
}
